package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"time"
)

func RemoteIp(request *http.Request) string {
	remoteAddr := request.RemoteAddr
	if ip := request.Header.Get("XRealIP"); ip != "" {
		remoteAddr = ip
	} else if ip = request.Header.Get("XForwardedFor"); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}

	return remoteAddr
}

func index(w http.ResponseWriter, request *http.Request) {
	// 遍历 request header，逐个写入到 response header 中
	for k, v := range request.Header {
		//tempStr := ""
		//for _, v1 := range v {
		//	tempStr += v1
		//}
		//w.Header().Add(k, tempStr)
		w.Header().Add(k, v[0])
	}

	// 读取当前系统环境变量 VERSION，添加写入到 response header 中
	envVERSION := os.Getenv("VERSION")
	w.Header().Add("VERSION", envVERSION)

	// 打印客户端 ip http 返回码
	clientIP := RemoteIp(request)
	httpStatusCode := http.StatusOK
	layout := "[2006-01-02 15:04:05.000]"
	fmt.Printf("%v client_ip: %v http_code: %v\n", time.Now().Format(layout), clientIP, httpStatusCode)

	_, err := fmt.Fprintf(w, "Response header:\n\n")
	if err != nil {
		return
	}
	for k, v := range w.Header() {
		_, err2 := fmt.Fprintf(w, "%v: '%v'\n", k, v[0])
		if err2 != nil {
			return
		}
	}

}

func healthz(w http.ResponseWriter, request *http.Request) {
	w.WriteHeader(200)
	_, err := fmt.Fprintf(w, "OK\n")
	if err != nil {
		return
	}
}

func main() {
	server := http.Server{
		Addr: ":8080",
	}
	http.HandleFunc("/", index)
	http.HandleFunc("/healthz", healthz)

	if err := server.ListenAndServe(); err != nil {
		log.Fatal("ERROR: ", err)
	}
}
